import { useMutation, useQuery } from 'react-query';
import { request } from '@/request';
import { useHistory, useParams } from 'react-router-dom';
import { useGlobalVar } from '@/hooks';

type Payload = {
    bill_desc: string;
    category: string;
    account: number;
    members: Array<string>
    details: Array<{ user: string, account: number }>;
};

const formatData = (res) => {
    if (!res) return null
    const { account, category, mode, bill_desc, details } = res.data
    return {
        account,
        desc: bill_desc,
        // members: details.map((item) => item.userId),
        members: details.map((item) => ({
            userId: item.userId,
            username: item.username
        })),
        category,
        mode,
        details
    }
}
const useBillEditor = () => {
    const { groupId } = useGlobalVar();

    const history = useHistory();

    const { id } = useParams();
    const isNew = id === undefined

    // 账单参数
    const initParams = {
        category: null,
        account: '0',
        desc: '',
        members: [],
        mode: 'average',
        details: [],
    }

    // 初始账单
    const { data, isLoading } = useQuery(
        'bill',
        async () => request(`/bill`, {
            params: {
                id,
            },
        }),
        {
            enabled: id !== undefined,
        }
    );

    // 添加账单
    const { mutate: addBill } = useMutation({
        mutationFn: (data: Payload) =>
            request(`/bills/byGroup/${groupId}`, {
                method: 'POST',
                data,
                showSuccess: true,
                success: () => {
                    history.push('/home');
                },
            }),
    });

    const { mutate: updateBill } = useMutation({
        mutationFn: (data: Payload) =>
            request(`/bills/${id}`, {
                method: 'PATCH',
                data,
                showSuccess: true,
                success: () => {
                    window.history.back();
                },
            }),
    });



    return {
        updateBill,
        addBill,
        isNew,
        data: isNew ? initParams : formatData(data),
        loading: isNew ? false : isLoading
    }
}

export default useBillEditor